//
//  HD_HSP_Friends_ViewController.m
//  HDLiaoNingMeseum
//
//  Created by HDHaoShaoPeng on 2017/8/5.
//  Copyright © 2017年 HDNiuKuiming. All rights reserved.
//

#import "HD_HSP_Friends_ViewController.h"
#import "HD_HSP_Mine_Model.h"
#import "UIView+Extension.h"

@interface HD_HSP_Friends_ViewController ()<UITableViewDataSource,UITableViewDelegate, UIAlertViewDelegate, UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
@property (weak, nonatomic) IBOutlet UIButton *addButton;
@property (weak, nonatomic) IBOutlet UITableView *myTabelView;
@property (weak, nonatomic) IBOutlet UILabel *myTitleLabel;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *viewWidthConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *viewLeadingConstraint;

@property (weak, nonatomic) IBOutlet UILabel *groupNumLabel;
@property (weak, nonatomic) IBOutlet UIScrollView *myScrollView;

@property(strong,nonatomic)NSMutableArray *friendsArray;
@end

static HDDeclare *declare;
@implementation HD_HSP_Friends_ViewController
{
    NSString *_inputNumber;
}

-(NSMutableArray *)friendsArray
{
    if (!_friendsArray) {
        _friendsArray = [NSMutableArray arrayWithCapacity:50];
    }
    return _friendsArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    declare = [HDDeclare sharedDeclare];
    
    
    self.myTitleLabel.text = declare.myFriend;
    self.myTitleLabel.font = [UIFont fontWithName:@"FZQKBYSJW--GB1-0" size:18.0];
    
    
    UIColor  *backgroundColor=[UIColor colorWithRed:103/255.0 green:88/255.0 blue:74/255.0 alpha:1.0];
    //字体
    UIFont *font=[UIFont boldSystemFontOfSize:18.0];
    NSDictionary *attrsDic=@{
                             NSForegroundColorAttributeName:backgroundColor,
                             NSFontAttributeName:font
                             };
    NSAttributedString *attriStr = [[NSAttributedString alloc]initWithString:declare.registerGroup attributes:attrsDic];
    NSAttributedString *joinStr = [[NSAttributedString alloc]initWithString:declare.joinGroup attributes:attrsDic];
    
    [self.registerBtn setAttributedTitle:attriStr forState:UIControlStateNormal];
    [self.addButton setAttributedTitle:joinStr forState:UIControlStateNormal];
    
    self.registerBtn.titleEdgeInsets = UIEdgeInsetsMake(50.0, 0, 0, 0);
    self.addButton.titleEdgeInsets = UIEdgeInsetsMake(50.0, 0, 0, 0);
    
    if (declare.group_name.integerValue != 0) {
        self.viewLeadingConstraint.constant = -kScreenWidth;
        self.groupNumLabel.text = [NSString stringWithFormat:@"%@%@",declare.groupLabel,declare.group_name];
        [self getMyFriends];
    }
    self.viewWidthConstraint.constant = kScreenWidth*2;
    [self.myScrollView layoutIfNeeded];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)getMyFriends
{
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@",[HDDeclare IP_Request_Header],@"index.php?g=mapi&m=Friend&a=get_group_member"];
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:declare.userID,@"device_id",nil];
    [HD_LY_NetHelper requestWithType:POST withUrl:requestUrl withParams:params toShowVC:self success:^(id response) {
        NSDictionary *dicData = response;
        if ([dicData[@"status"] intValue] == 1)
        {
            NSArray *tempArr = [dicData objectForKey:@"data"];
            [self.friendsArray removeAllObjects];
            for (NSDictionary *tempDic in tempArr) {
                HD_HSP_Mine_Model *model = [[HD_HSP_Mine_Model alloc]init];
                model.is_dlj = [tempDic objectForKey:@"is_dlj"];
                model.name = [tempDic objectForKey:@"device_id"];
                model.nick_name = [tempDic objectForKey:@"nick_name"];
                [self.friendsArray addObject:model];
            }
            
            [self.myTabelView reloadData];
            
        }else {
            
        }
    } fail:^(NSError *error) {
        
    } showHUD:NO isCache:NO];
}


#pragma mark - 私有方法
-(void)joinGroup
{
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@",[HDDeclare IP_Request_Header],@"index.php?g=mapi&m=Friend&a=add_group"];
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:declare.userID,@"device_id",_inputNumber,@"group",nil];
    [HD_LY_NetHelper requestWithType:POST withUrl:requestUrl withParams:params toShowVC:self success:^(id response) {
        NSDictionary *dicData = response;
        if ([dicData[@"status"] intValue] == 1)
        {
            declare.group_name = [dicData objectForKey:@"data"];
            self.groupNumLabel.text = [NSString stringWithFormat:@"%@%@",declare.groupLabel,declare.group_name];
            [self getMyFriends];
            self.viewLeadingConstraint.constant = -kScreenWidth;
            [self.myScrollView layoutIfNeeded];
        }
        else
        {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            // Set the text mode to show only text.
            hud.mode = MBProgressHUDModeText;
            hud.label.text = NSLocalizedString([dicData objectForKey:@"msg"], @"HUD message title");
            // Move to bottm center.
            hud.offset = CGPointMake(0.f, 200);
            [hud hideAnimated:YES afterDelay:2.f];
        }
    } fail:^(NSError *error) {
        
    } showHUD:NO isCache:NO];
}


#pragma mark - 点击方法

- (IBAction)quitGroup:(id)sender {
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@",[HDDeclare IP_Request_Header],@"index.php?g=mapi&m=Friend&a=del_group"];
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:declare.userID,@"device_id",declare.group_name,@"group",nil];
    [HD_LY_NetHelper requestWithType:POST withUrl:requestUrl withParams:params toShowVC:self success:^(id response) {
        NSDictionary *dicData = response;
        if ([dicData[@"status"] intValue] == 1)
        {
            self.viewLeadingConstraint.constant = 0;
            [self.myScrollView layoutIfNeeded];
        }
        else
        {
            
        }
    } fail:^(NSError *error) {
        
    } showHUD:NO isCache:NO];
}



- (IBAction)registerClicked:(id)sender {
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@",[HDDeclare IP_Request_Header],@"index.php?g=mapi&m=Friend&a=request_group"];
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:declare.userID,@"device_id",nil];
    [HD_LY_NetHelper requestWithType:POST withUrl:requestUrl withParams:params toShowVC:self success:^(id response) {
        NSDictionary *dicData = response;
        if ([dicData[@"status"] intValue] == 1)
        {
            declare.group_name = [dicData objectForKey:@"data"];
            self.groupNumLabel.text = [NSString stringWithFormat:@"%@%@",declare.groupLabel,declare.group_name];
            [self getMyFriends];
            self.viewLeadingConstraint.constant = -kScreenWidth;
            [self.myScrollView layoutIfNeeded];
        }
        else
        {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            // Set the text mode to show only text.
            hud.mode = MBProgressHUDModeText;
            hud.label.text = NSLocalizedString([dicData objectForKey:@"msg"], @"HUD message title");
            // Move to bottm center.
            hud.offset = CGPointMake(0.f, 200);
            [hud hideAnimated:YES afterDelay:2.f];
        }
    } fail:^(NSError *error) {
        
    } showHUD:NO isCache:NO];
}

- (IBAction)addGroupClicked:(id)sender {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:declare.joinNumberNeed message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:declare.alertCancel style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:declare.alertOK style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        UITextField *login = alert.textFields.firstObject;
        _inputNumber = login.text;
        [self joinGroup];
    }];
    [alert addAction:cancelAction];
    [alert addAction:okAction];
    
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField){
//        textField.placeholder = @"登录";
    }];
    alert.textFields.firstObject.keyboardType = UIKeyboardTypeNumberPad;
    [self presentViewController:alert animated:YES completion:nil];
}


- (IBAction)backClicked:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}




#pragma mark - ------- TableView Delegate Methods --------

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 20)];
    label.textAlignment = NSTextAlignmentLeft;
    label.text = [NSString stringWithFormat:@"%@%@", declare.myGroupNumber,declare.groupNumber];
    
    // 本句用于总人数显示
    //    label.text = [NSString stringWithFormat:@"%@%@  %@%i", declare.myGroupNumber,declare.groupNumber, declare.myGroupTotalPersion, self.friendsArray.count];
    label.backgroundColor = [UIColor lightGrayColor];
    
    return label;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    
    return [self.friendsArray count];
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"cellForFriend";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell= [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    HD_HSP_Mine_Model *myfriend = self.friendsArray[indexPath.row];
    cell.textLabel.text = myfriend.nick_name;
    cell.detailTextLabel.text = myfriend.name;
    cell.imageView.image = [UIImage imageNamed:@"mine_friend_icon"];
    cell.backgroundColor = [UIColor clearColor];
    
    UIImageView *image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"cell_selected"]];
    cell.selectedBackgroundView = image;
    UIImageView *rightImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]];
    cell.accessoryView = rightImage;
    
    cell.textLabel.textColor = [UIColor blackColor];
    cell.detailTextLabel.textColor = [UIColor blackColor];
    NSString *strName = [NSString stringWithFormat:@"ios%@", declare.userID];
    if ([cell.detailTextLabel.text isEqualToString:strName])
    {
        cell.textLabel.textColor = [UIColor redColor];
        cell.detailTextLabel.textColor = [UIColor redColor];
    }
    
    cell.textLabel.font = [UIFont fontWithName:@"FZQKBYSJW--GB1-0" size:20.0];
    cell.detailTextLabel.font = [UIFont fontWithName:@"FZQKBYSJW--GB1-0" size:15.0];
    
    if (myfriend.is_dlj.integerValue != 0) {
        UIImage *imageRight = [UIImage imageNamed:@"friend_loc"];
        cell.accessoryView = [[UIImageView alloc] initWithImage:imageRight];
    }
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
